package cn.stylefeng.guns.modular.cb.service;

import cn.stylefeng.guns.modular.cb.util.RestResultEntity;
import cn.stylefeng.roses.core.util.ToolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.stream.FileImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FastDFSService {

    private static Logger logger = LoggerFactory.getLogger(FastDFSService.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上传文件
     * @param file
     * @return 文件id
     */
    public String uploadFile(MultipartFile file){
        String fileId = "";
        String path = "";
        try {
            path = System.getProperty("user.dir")+ File.separator+file.getOriginalFilename();
            File tempFile = new File(path);
            file.transferTo(tempFile);
            //fast文件上传
            FileSystemResource resource = new FileSystemResource(tempFile);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            RestResultEntity restResultEntity = restTemplate.postForObject("http://FASTDFS-CLIENT:8118/api/fastdfs/upload", param, RestResultEntity.class);
            if (restResultEntity.getErr()<0){
                logger.info("上传失败！");
            }else {
                fileId = restResultEntity.getData().toString();
            }
        } catch (IOException e) {
            logger.error("uploadFile error: ", e);
            fileId = "";
        }finally {
            try {
                Files.delete(Paths.get(path));
            } catch (IOException e) {
                logger.error("delete error: ", e);
            }
        }
        return fileId;
    }

    /**
     * 显示文件
     * @param fileId
     * @return
     */
    public HttpServletResponse streamFile(String fileId, HttpServletResponse response){
        String url = "http://FASTDFS-CLIENT:8118/api/fastdfs/stream_file?fileId="+fileId;
//        ResponseEntity responseEntity = restTemplate.headForHeaders(url);
        return response;
    }

    /**
     * 下载文件
     * 获取文件字节码
     * @param fileId
     * @return
     */
    public byte[] downloadByte(String fileId){
        String url = "http://FASTDFS-CLIENT:8118/api/fastdfs/download_file?fileId="+fileId;
        byte[] fileStream = restTemplate.getForObject(url, byte[].class);
        return fileStream;
    }

    /**
     * 下载文件
     * 文件落地，返回本地文件地址
     */
    public String downloadFile(String fileId){
        if (StringUtils.isEmpty(fileId)){
            return "";
        }
        String suffix = "doc";
        if(fileId.lastIndexOf(".") != -1 && fileId.lastIndexOf(".") != 0){
            suffix = fileId.substring(fileId.lastIndexOf(".")+1);
        }
        String url = "http://FASTDFS-CLIENT:8118/api/fastdfs/download_file?fileId="+fileId;
        byte[] fileStream = restTemplate.getForObject(url, byte[].class);
        String path = System.getProperty("user.dir")+ File.separator+ UUID.randomUUID()+"."+suffix;
        byte2image(fileStream, path);
        return path;
    }


    /**
     * 删除文件
     * 返回值为 “” 表示删除成功
     */
    public String deleteFile(String fileId){
        String url = "http://FASTDFS-CLIENT:8118/api/fastdfs/delete_file?fileId="+fileId;
        RestResultEntity restResultEntity = restTemplate.getForObject(url, RestResultEntity.class);
        return restResultEntity.getErrMsg();
    }

    //byte数组到图片
    public void byte2image(byte[] data,String path){
        if(data.length<3||path.equals("")) return;
        try (FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));) {
            imageOutput.write(data, 0, data.length);
            imageOutput.close();
            logger.info("Make Picture success,Please find image in {}", path);
        } catch(Exception ex) {
            logger.error("Exception: " + ex);
        }
    }

    /**
     * 获取文件类型
     * @param fileId
     * @return
     */
//    public String fileType(String fileId){
//        String fileSuffix = ToolUtil.getFileSuffix(file.getOriginalFilename());
//    }
}
